﻿using System.IO;
using System.Reflection;
using AccessBasedDesktop.Core;
using CommandLine;
using CommandLine.Text;
using log4net.Config;

namespace AccessBasedDesktop.Processor
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string configFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                @"log4net.config.xml");
            XmlConfigurator.Configure(new FileInfo(configFileName));

            var clo = new CommandLineOptions();
            if (Parser.Default.ParseArguments(args, clo))
            {
                Options opt = Options.LoadFromFile();
                opt.SaveToFile();

                if (!string.IsNullOrEmpty(clo.OptionsFileName))
                    opt = Options.LoadFromFile(clo.OptionsFileName);

                if (!string.IsNullOrEmpty(clo.DesktopSourceDir))
                    opt.DesktopSourceDir = clo.DesktopSourceDir;

                if (!string.IsNullOrEmpty(clo.DomainName))
                    opt.DomainName = clo.DomainName;

                using(var manager = new Manager(opt))
                    manager.UpdateAllDesktops();
            }
        }
    }

    internal class CommandLineOptions
    {
        [Option('o', "options", Required = false,
            HelpText = "Options file name.")]
        public string OptionsFileName { get; set; }

        [Option('s', "source", Required = false,
            HelpText = "Desktop source directory name.")]
        public string DesktopSourceDir { get; set; }

        [Option('m', "domain", Required = false,
            HelpText = "Domain name.")]
        public string DomainName { get; set; }

        [ParserState]
        public IParserState LastParserState { get; set; }

        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this,
                current => HelpText.DefaultParsingErrorsHandler(this, current));
        }
    }
}